import type { MutationTree, ActionTree, GetterTree } from 'vuex'
import type { IRootState } from './index'
import { Actions, Mutations } from '@/enum/portal'
import { detail, detailOne, IDetailParams, IDetailOneParams } from '@/api/commonInstance'
import { DBNames } from '@/enum/dbName'

export interface IPortal {
  createdBy: string
  createdTime: string
  customerId: string
  data: Record<string, unknown>
  id: string
  _id?: string // 临时兼容
  isDeleted: number
  orgId: string
  ownerId: string
  status?: string
  templateName: string
  updatedBy: string
  updatedTime: string
}
export interface IPortalState {
  portalObj: IPortal
}

export const state: () => IPortalState = () => ({
  portalObj: {
    createdBy: '',
    createdTime: '',
    customerId: '',
    data: {},
    id: '',
    _id: '',
    isDeleted: 0,
    orgId: '',
    ownerId: '',
    status: '',
    templateName: '',
    updatedBy: '',
    updatedTime: '',
  },
})

export const mutations: MutationTree<IPortalState> = {
  [Mutations.SET_PORTAL](state, payload) {
    state.portalObj = payload
  },
}

export const actions: ActionTree<IPortalState, IRootState> = {
  async [Actions.getPortalById]({ commit }, id: string) {
    const params: IDetailParams = {
      id,
      templateName: DBNames.B_CONSOLE_PARK,
    }

    const result: any = await detail(params)
    console.log(result)

    commit(Mutations.SET_PORTAL, result || {})
    return result
  },

  async [Actions.getPortalByCustomId]({ commit }) {
    const params: IDetailOneParams = {
      templateName: DBNames.B_CONSOLE_PARK,
      conditions: {},
    }
    const result: any = await detailOne(params)
    console.log(result)
    commit(Mutations.SET_PORTAL, result || {})
    return result
  },
}

export const getters: GetterTree<IPortalState, IRootState> = {
  portalId: (state) => state.portalObj.id || state.portalObj._id,
  portalData: (state) => state.portalObj.data,
  recommendProject: (state) => state.portalObj.data.recommendProject,
  recommendLand: (state) => state.portalObj.data.recommendLand,
  recommendBuilding: (state) => state.portalObj.data.recommendBuilding,
  recommendWorkshop: (state) => state.portalObj.data.recommendWorkshop,
  recommendDepository: (state) => state.portalObj.data.recommendDepository,
  recommendShop: (state) => state.portalObj.data.recommendShop,
}
